# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : plugin_used_view.py
# Time       ：2023/11/2 16:46
# Author     ：YangYong
# version    ：python 3.10
# Description：插件使用统计
"""
from typing import List

from flask_restx import Resource, fields
from sqlalchemy import func

from apis.data_screen import data_screen_ns
from apis.data_screen.schema.plugin_use_schema import PluginUseSchema
from apis.orderlines.models import Task
from apis.plugin.models.plugin_info import PluginInfo
from apis.plugin.schema.plugin_info_schema import PluginInfoSchema
from public.api_utils.api_decorator import handle_api_error
from public.base_model import db
from public.base_response import generate_response, MarshalModel

plugin_used = {
    'name': fields.String(description='插件名称'),
    'value': fields.String(description='插件数量'),
    'percentage': fields.String(description='使用比例'),

}

plugin_used_marshal = MarshalModel('plugin_use', data_screen_ns)


class PluginUsedView(Resource):
    url = '/plugin_use'

    def __init__(self, *args, **kwargs):
        super(PluginUsedView, self).__init__(*args, **kwargs)
        self.total = 0

    @staticmethod
    def get_plugin_title(plugin_info: List[dict], model_name: str):
        for item in plugin_info:
            if item.get('class_name') == model_name:
                return item.get('plugin_title')
        return model_name

    @handle_api_error()
    @data_screen_ns.doc(description='插件使用统计')
    @data_screen_ns.expect(plugin_used_marshal.list_response(plugin_used, True, False))
    def get(self):
        """插件使用统计"""
        objs = db.session.query(PluginInfo).filter(PluginInfo.active == 1).all()
        plugin_info = PluginInfoSchema().dump(objs, many=True)

        response_data = list()
        objs = db.session.query(
            Task.task_module.label('name'),
            func.count(1).label('value')
        ).filter(Task.active == 1).group_by('name').all()
        info = PluginUseSchema().dump(objs, many=True)
        for item in info:
            self.total = self.total + item.get('value') or 0
        for item in info:
            response_data.append(
                {
                    'name': self.get_plugin_title(plugin_info, item.get('name')),
                    'value': item.get('value'),
                    'percentage': f"{round(item.get('value') / self.total * 100)}%",
                }
            )

        response_data.sort(key=lambda val: val.get('value'), reverse=True)
        return generate_response(response_data[0:4])
